﻿using MediatR;
using T.Basic.Domain.T.Basic.Dto;
using T.Basic.Domain.T.Basic.Model;
using T.Basic.Read.API.Appliction.Command.OutsourcedUnitsCommand;
using T.Basic.Repository.BasicImpl;
using T.Basic.Repository.BasicInterface;

namespace T.Basic.Read.API.Appliction.CommandHandlers.OutsourcedUnitsCommandHanders
{
    /// <summary>
    /// 显示外协单位信息
    /// </summary>
    public class OutsourcedUnitsListCommandHanders : IRequestHandler<OutsourcedUnitsListCommand, PageDto<OutsourcedUnits>>
    {
        private readonly IOutsourcedUnitsRepository _outsourcedUnitsRepository;
        public OutsourcedUnitsListCommandHanders(IOutsourcedUnitsRepository outsourcedUnitsRepository)
        {
            _outsourcedUnitsRepository = outsourcedUnitsRepository;
        }
        public async Task<PageDto<OutsourcedUnits>> Handle(OutsourcedUnitsListCommand request, CancellationToken cancellationToken)
        {
            PageDto<OutsourcedUnits> pageDto = new PageDto<OutsourcedUnits>();
         
            var outlist = from a in await _outsourcedUnitsRepository.GetAllAsync()
                           where !a.IsDeleted
                           select a;
            if (!string.IsNullOrEmpty(request.CompanyID))
            {
                outlist = outlist.Where(d => d.CompanyID == request.CompanyID).ToList();
            }
            if (!string.IsNullOrEmpty(request.OutsourcedUnitsName))
            {
                outlist= outlist.Where(d=>d.OutsourcedUnitsName.Contains(request.OutsourcedUnitsName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.OutsourcedUnitsPhone))
            {
                outlist = outlist.Where(d => d.OutsourcedUnitsPhone.Contains(request.OutsourcedUnitsPhone)).ToList();
            }
            if (request.PageIndex == null)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize == null)
            {
                request.PageSize = outlist.Count();
            }
            var index=request.PageIndex;
            var size=request.PageSize;
            pageDto.TotalCount=outlist.Count();
            pageDto.PageCount = (int)Math.Ceiling(pageDto.TotalCount*1.0/(int)size);
            pageDto.list = outlist.OrderByDescending(d => d.CreatedDate).Skip(((int)index - 1) * (int)size).Take((int)size).ToList();
            return pageDto;
        }
    }
}
